package com.shanghaionstar.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.SparseArray;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.PublicService;
import com.onstar.cn.api.ThirdpartyService;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.network.BaseRequest;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.mag.publicService.H5DispatcherEntity;
import com.onstar.cn.mag.publicService.PreferentialReqEntity;
import com.onstar.cn.mag.publicService.response.H5DispatcherResEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.shanghaionstar.activity.webview.handler.BannerWebHandler;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.enumtype.OSTypeEnum;
import com.shanghaionstar.report.bean.ReportReqParam;

import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;

/**
 * Created by 7828wc on 16/7/13.
 */
public class BannerUtil {

    private Context context;

    public BannerUtil(Context context) {
        this.context = context;
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.ZH), method = HttpMethod.PUT)
    public String commandDataJson(String type) throws OnStarException {
        PublicService publicService = new PublicService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        PreferentialReqEntity entity = new PreferentialReqEntity();
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getCurrentVehicle())) {
            entity.setVin(ApplicationUtil.getInstance().getCurrentVehicle().getVin());
            entity.setMake(ApplicationUtil.getInstance().getCurrentVehicle().getMake());
            entity.setModel(ApplicationUtil.getInstance().getCurrentVehicle().getModel());
            entity.setYear(ApplicationUtil.getInstance().getCurrentVehicle().getYear());
        }
        entity.setDeviceType("10");
        entity.setDeviceOS(OSTypeEnum.ANDROID.value());
        entity.setLanguagePreference(Language.ZH.value());
        entity.setUserID(ApplicationUtil.getInstance().getIdpID());
        entity.setImgType(OSTypeEnum.ANDROID.value());
        entity.setCategory(type);
        String versionCode = new DeviceUtil(context).getAppVersionCode() + "";
        entity.setVersionCode(versionCode + "");
        requestEntity = publicService.getBanner(requestEntity, entity);
        requestEntity.setUrl(requestEntity.getUrl());
        requestEntity = HttpInjectUtils.injectHttp(BannerUtil.this.getClass(), "commandDataJson", requestEntity, String.class);
        return BusinessUtil.getResponse(getDatas(requestEntity), context);
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String h5DispatcherJson(PreferentialResEntity entity) throws OnStarException {
        ThirdpartyService thirdpartyService = new ThirdpartyService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        H5DispatcherEntity h5DispatcherEntity = new H5DispatcherEntity();
        h5DispatcherEntity.setAttributeData(entity.getAttributeData());
        h5DispatcherEntity.setContentType(entity.getContentType());
        h5DispatcherEntity.setMethod(entity.getHttpMethod());
        h5DispatcherEntity.setParamsData(entity.getParamData());
        h5DispatcherEntity.setUrl(entity.getUrl());
        h5DispatcherEntity.setPartner_id(entity.getPartnerId());
        //lat,long
        requestEntity = thirdpartyService.h5Dispatcher(requestEntity, h5DispatcherEntity);
        requestEntity = HttpInjectUtils.injectHttp(BannerUtil.this.getClass(), "h5DispatcherJson", requestEntity, PreferentialResEntity.class);
        return BusinessUtil.getResponse(getDatas(requestEntity), context);
    }

    public Observable<H5DispatcherResEntity> h5Dispatcher(final PreferentialResEntity entity) {
        return Observable.defer(new Func0<Observable<H5DispatcherResEntity>>() {
            @Override
            public Observable<H5DispatcherResEntity> call() {
                try {
                    H5DispatcherResEntity result = new Gson().fromJson(h5DispatcherJson(entity), H5DispatcherResEntity.class);
                    return Observable.just(result);
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<Map<String, List<PreferentialResEntity>>> commandData(final String type) {
        return Observable.defer(new Func0<Observable<Map<String, List<PreferentialResEntity>>>>() {
            @Override
            public Observable<Map<String, List<PreferentialResEntity>>> call() {
                try {
                    Map<String, List<PreferentialResEntity>> result = new Gson().fromJson(commandDataJson(type), new TypeToken<Map<String, List<PreferentialResEntity>>>() {
                    }.getType());
                    return Observable.just(result);
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    interface ShowType {
        String NATIVE_TYPE = "1";
        String DISPATCHER_TYPE = "3";
        String DIRECTIVE_TYPE = "4";
    }


    private void reportPartner(String url) {
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity.setUrl(url);
        requestEntity.setMethod(HttpMethod.GET.value());
        new Sender().send(requestEntity);
    }

    private void launchBannerActivity(Context mContext, String url, ResponBannerEntity entity) {
        WebDataEntity mWebData = new WebDataEntity();
        mWebData.setLinkUrl(url);
        mWebData.setWhat(IWebType.TYPE_BANNER);
        mWebData.setTopTitle(entity.getTitle());
        mWebData.setClzName(BannerWebHandler.class.getName());
        CommonWebViewActivity.launchCommonWeb((Activity) mContext,mWebData,entity);
    }

    public void bannerClick(final ResponBannerEntity entity, final Context mContext, FunctionNameFindId functionNameFindId, IMVPScheduler mvpScheduler, final IMVPView view) {
        if (entity == null)
            return;
        //上传秒针
        if (!TextUtils.isEmpty(entity.getClickMonitoringUrl()))
            reportPartner(entity.getClickMonitoringUrl());
        //上传reprot
        if (functionNameFindId != null && functionNameFindId != FunctionNameFindId.UnSend)
            BusinessUtil.sendReportByRequestParams(mContext, functionNameFindId.getStringValue(), ReportReqParam.getBannerClickReqParm(entity.getBannerID()));
        //处理跳转
        String showType = entity.getShowType();
        jumpToBannerActivity(entity, mContext, mvpScheduler, view, showType);
    }

    private void jumpToBannerActivity(final ResponBannerEntity entity, final Context mContext, IMVPScheduler mvpScheduler, final IMVPView view, String showType) {
        if (TextUtils.isEmpty(showType))
            return;
        if (ShowType.DISPATCHER_TYPE.equalsIgnoreCase(showType)) {
            jumpH5Dispatcher(entity, mContext, mvpScheduler, view);
        } else if (ShowType.DIRECTIVE_TYPE.equals(showType)) {
            jumpToBrowser(entity, mContext);
        }

    }

    private void jumpToBrowser(ResponBannerEntity entity, Context mContext) {
        Intent intent = new Intent();
        String paramData = entity.getParamData();
        String url = TextUtils.isEmpty(entity.getContentUrl())
                ? entity.getUrl() : entity.getContentUrl();
        intent.setAction("android.intent.action.VIEW");
        if (!TextUtils.isEmpty(paramData)) {
            url += "&data=" + paramData;
        }
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        mContext.startActivity(intent);
    }

    private void jumpH5Dispatcher(final ResponBannerEntity entity, final Context mContext, IMVPScheduler mvpScheduler, final IMVPView view) {
        if(view != null)
            view.setLoading(true);
        if(entity instanceof PreferentialResEntity)
            h5Dispatcher((PreferentialResEntity) entity).subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<H5DispatcherResEntity>() {
                @Override
                public void call(H5DispatcherResEntity mResult) {
                    if(view != null)
                        view.setLoading(false);
                    String url = mResult.getUrl();
                    launchBannerActivity(mContext, url, entity);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    if(view != null)
                        view.setLoading(false);
                }
            });
    }


    public Observable<List<ResponBannerEntity>> commandDataList(final String type) {
        return Observable.defer(new Func0<Observable<List<ResponBannerEntity>>>() {
            @Override
            public Observable<List<ResponBannerEntity>> call() {
                try {
                    List<ResponBannerEntity> result = new Gson().fromJson(commandDataJson(type), new TypeToken<List<PreferentialResEntity>>() {
                    }.getType());
                    return Observable.just(result);
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    /**
     * 做数据请求，获取响应数据
     *
     * @return
     */
    public SparseArray<String> getDatas(RequestEntity requestEntity) {
        BaseRequest request = new BaseRequest(requestEntity);
        return request.excute();
    }

}
